package com.mayikt.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.manager.SpikeManager;
import com.mayikt.mapper.OrderMapper;
import com.mayikt.mapper.SeckillMapper;
import com.mayikt.service.SpikeCommodityService;
import com.mayikt.utils.RedisUtil;
import com.mayikt.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpikeCommodityServiceImpl extends BaseApiService implements SpikeCommodityService {

    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SpikeManager spikeManager;

    @Override
    public BaseResponse<JSONObject> spike(String userPhone, Long seckillId) {
        // 1.验证参数
        if (userPhone == null) {
            return setResultError("userPhone不能为空");
        }
        if (seckillId == null) {
            return setResultError("seckillId不能为空");
        }
//        // 2.对用户的频率实现限制 10s setnx key存在返回1 key如果不存在的情况0
//        Boolean spikeNx = redisUtil.setNx(userPhone, seckillId + "", 10l);
//        if (!spikeNx) {
//            return setResultError("您当前在10s内访问频率过多,请稍后重试!");
//        }
        // 3. 从Redis中获取令牌，
        String spikeToken = tokenUtil.getListKeyToken(seckillId + "");
        if (StringUtils.isEmpty(spikeToken)) {
            return setResultError("很抱歉，当前商品已经售空，请下次再来");
        }
        // 4.修改库存、下订单 肯定不同步 一定要是异步实现 MQ异步实现     // 投递消息到MQ中
        spikeManager.sendSpikeMsg(userPhone, seckillId, spikeToken);
        return setResultError("正在抢购中...");
    }
}
